//
//  GroupIMNet.m
//  SportSocial
//
//  Created by yull on 14/12/23.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "GroupIMNet.h"
#import "GroupMsgDao.h"
#import "ChatInfoDao.h"
#import "CurrentChat.h"
#import "IMNet.h"

@implementation GroupIMNet

+ (instancetype)shareInstance
{
    static GroupIMNet *groupNet = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        groupNet = [[GroupIMNet alloc] init];
    });
    return groupNet;
}

- (instancetype)init
{
    if (self = [super init]) {
        
        self.msgArray = [NSMutableArray array];
        
        NSArray *pidArray = @[[NSNumber numberWithInteger:Group_RecMsg_Receive_PID],
                          [NSNumber numberWithInteger:Group_SendMsg_Receive_PID]];
        [self.arrayPid addObjectsFromArray:pidArray];
        
        self.timer = [NSTimer scheduledTimerWithTimeInterval:60.0f
                                                      target:self
                                                    selector:@selector(handleTimer:)
                                                    userInfo:nil
                                                     repeats:YES];
    }
    return self;
}

#pragma mark - 发送消息

- (void)sendGroupTextMsg:(GroupChatMsg *)chatMsg isResend:(BOOL)resend
{
    BOOL ret = NO;
    if (!resend) {
        ret = [[GroupMsgDao shareInstance] insertGroupChatMsg:chatMsg];
    }else {
        ret = [[GroupMsgDao shareInstance] updateChatMsg:chatMsg];
    }
    
    ChatInfo *chatInfo = [ChatInfo chatInfoWithGroupMsg:chatMsg];
    ret &= [[ChatInfoDao shareInstance] addOrUpdateChatInfo:chatInfo];
    
    if (ret) {
        
        if (![FunctionMethod networkAvailable] || ![IM_Service instance].isConnected) {
            chatMsg.sendStatus = ChatMsgSendStatusFail;
        }else {
            
            [self.msgArray addObject:chatMsg];
            
            ChatMsgBody_Builder *builder = [[ChatMsgBody builder] setMsgNum:chatMsg.dbId];
            builder = [builder setSendId:[CurrentUser shareInstance].userId];
            builder = [builder setSenderName:[CurrentUser shareInstance].name];
            builder = [builder setMsg:chatMsg.content];
            builder = [builder setCreateTime:[[NSDate date] timeIntervalSince1970]];
            builder = [builder setMsgType:ChatMsgTypeText];
            builder = [builder setCreateTime:chatMsg.createTime];
            
            GroupChatMsgCG *groupMsg = [[[[GroupChatMsgCG builder] setChatMsg:[builder build]] setGroupId:chatMsg.groupId] build];
            
            NSData *data = [groupMsg data];
            
            [[IM_Service instance] sendData:data protocolId:Group_SendMsg_Send_PID];
        }
        
        if (resend) {
            [self updateSendStatusWithDbId:chatMsg.dbId status:chatMsg.sendStatus];
        }else {
            [self sendInsertChatMsgNotificationWithMsgArray:[NSArray arrayWithObject:chatMsg]];
        }
    }
}

- (void)sendGroupAudioMsg:(GroupChatMsg *)chatMsg audioData:(NSData *)audioData isResend:(BOOL)resend;
{
    BOOL ret = NO;
    if (!resend) {
        ret = [[GroupMsgDao shareInstance] insertGroupChatMsg:chatMsg];
    }else {
        ret = [[GroupMsgDao shareInstance] updateChatMsg:chatMsg];
    }
    
    ChatInfo *chatInfo = [ChatInfo chatInfoWithGroupMsg:chatMsg];
    ret &= [[ChatInfoDao shareInstance] addOrUpdateChatInfo:chatInfo];
    
    if (ret) {
        
        [IMNet sendGroupAudioWithData:audioData groupId:chatMsg.groupId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSString *url = [responseObject objectForKey:@"data"];
            if ([[GroupMsgDao shareInstance] updateMsgId:chatMsg.dbId preview:url original:@""]) {
                NSLog(@"更新语音地址成功!");
            }else {
                NSLog(@"更新语音地址失败!");
            }
            [self updateSendStatusWithDbId:chatMsg.dbId status:ChatMsgSendStatusSuccess];
        } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self updateSendStatusWithDbId:chatMsg.dbId status:ChatMsgSendStatusFail];
        }];
        
        if (resend) {
            [self updateSendStatusWithDbId:chatMsg.dbId status:chatMsg.sendStatus];
        }else {
            [self sendInsertChatMsgNotificationWithMsgArray:[NSArray arrayWithObject:chatMsg]];
        }
    }
}

- (void)sendGroupPicMsg:(GroupChatMsg *)chatMsg imageData:(NSData *)imageData isResend:(BOOL)resend;
{
    BOOL ret = NO;
    if (!resend) {
        ret = [[GroupMsgDao shareInstance] insertGroupChatMsg:chatMsg];
    }else {
        ret = [[GroupMsgDao shareInstance] updateChatMsg:chatMsg];
    }
    
    ChatInfo *chatInfo = [ChatInfo chatInfoWithGroupMsg:chatMsg];
    ret &= [[ChatInfoDao shareInstance] addOrUpdateChatInfo:chatInfo];
    
    if (ret) {

        AFHTTPRequestOperation *operation = [IMNet sendGroupPicWithData:imageData groupId:chatMsg.groupId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"上传群图片:%@",responseObject);
            
            NSDictionary *dataDict = [responseObject objectForKey:@"data"];
            NSString *original_img = [dataDict objectForKey:@"original_img"];
            NSString *preview_img = [dataDict objectForKey:@"preview_img"];
            chatMsg.url = preview_img;
            chatMsg.bigImageUrl = original_img;
            
            if ([[GroupMsgDao shareInstance] updateMsgId:chatMsg.dbId preview:preview_img original:original_img]) {
                NSLog(@"更新图片地址成功!");
            }else {
                NSLog(@"更新图片地址失败!");
            }
            [self updateSendStatusWithDbId:chatMsg.dbId status:ChatMsgSendStatusSuccess];
        } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self updateSendStatusWithDbId:chatMsg.dbId status:ChatMsgSendStatusFail];
        }];
        
        [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
            
            NSInteger percent = totalBytesWritten * 100.0f / totalBytesExpectedToWrite;
            
            NSDictionary *dict = @{@"msgId":[NSNumber numberWithLongLong:chatMsg.dbId],
                                   @"percent":[NSNumber numberWithInt:percent]};
            [[NSNotificationCenter defaultCenter] postNotificationName:@"UploadChatPicPercent" object:nil userInfo:dict];
        }];
        
        if (resend) {
            [self updateSendStatusWithDbId:chatMsg.dbId status:chatMsg.sendStatus];
        }else {
            [self sendInsertChatMsgNotificationWithMsgArray:[NSArray arrayWithObject:chatMsg]];
        }
    }
}

//收到群消息广播返回
- (void)test1
{
    //GroupNoticeCGMessage
}

- (void)sendAckWithMsgArray:(NSArray *)msgArray
{
    GroupChatNotifyCG_Builder *notifyBuilder = [GroupChatNotifyCG builder];
    for (GroupChatMsgBody *groupMsg in msgArray) {
        GroupChatNotify_Builder*builder =[GroupChatNotify builder];
        builder = [builder setGroupId:groupMsg.groupId];
        for (ChatMsgBody *msgBody in groupMsg.msgBodyList) {
            builder = [builder addMsgNum:msgBody.msgNum];
        }
        GroupChatNotify *notify = [builder build];
        notifyBuilder = [notifyBuilder addRevieveInfo:notify];
    }
    GroupChatNotifyCG *notifyCG = [notifyBuilder build];
    NSData *data = [notifyCG data];
    
    [[IM_Service instance] sendData:data protocolId:Group_Ack_Send_PID];
}

//发送群提醒  用于确定客户端是否收到群广播提醒
- (void)test5
{
    //GroupNoticeCGMessage
}

#pragma mark - 收到消息
- (void)handlePacketWithPid:(NSInteger)pid recvData:(NSData *)recvData
{
    switch (pid) {
        case Group_RecMsg_Receive_PID:
            [self handleReceiveMsgWithRecvData:recvData];
            break;
        case Group_SendMsg_Receive_PID:
            [self handleSendMsgResponseWithRecvData:recvData];
            break;
        default:
            [super handlePacketWithPid:pid recvData:recvData];
            break;
    }
}

//收到群聊消息
- (void)handleReceiveMsgWithRecvData:(NSData *)recvData
{
    GroupChatNotifyGC *groupMsg = [GroupChatNotifyGC parseFromData:recvData];
    
    if (groupMsg.groupChatList.count > 0) {
        BOOL result = YES;
        NSMutableArray *receiveArray = [NSMutableArray array];
        for (GroupChatMsgBody *groupMsgBody in groupMsg.groupChatList) {
            for (ChatMsgBody *msgBody in groupMsgBody.msgBodyList) {
                GroupChatMsg *chatMsg = [GroupChatMsg groupChatMsgWithMsg:msgBody];
                chatMsg.groupId = groupMsgBody.groupId;
                chatMsg.groupName = groupMsgBody.groupName;
                chatMsg.groupIcon = groupMsgBody.groupIcon;
                [receiveArray addObject:chatMsg];
                
                if ([[GroupMsgDao shareInstance] checkExistWithChatMsg:chatMsg]) {
                    result &= [[GroupMsgDao shareInstance] updateChatMsg:chatMsg];
                }else {
                    result &= [[GroupMsgDao shareInstance] insertGroupChatMsg:chatMsg];
                    
                    ChatInfo *chatInfo = [ChatInfo chatInfoWithGroupMsg:chatMsg];
                    chatInfo.name = groupMsgBody.groupName;
                    result &= [[ChatInfoDao shareInstance] addOrUpdateChatInfo:chatInfo];
                }
            }
        }
        if (result) {
            //接收消息并且保存成功
            NSLog(@"信息保存成功!");
            
            [SoundManager playSound];
            
            [self sendInsertChatMsgNotificationWithMsgArray:receiveArray];
            
            [self sendAckWithMsgArray:groupMsg.groupChatList];
        }
    }
}

//群聊消息发送后反馈
- (void)handleSendMsgResponseWithRecvData:(NSData *)recvData
{
    GroupChatMsgGC *groupChatMsg = [GroupChatMsgGC parseFromData:recvData];
    
    UInt64 msgNum = groupChatMsg.msgNum;
    UInt32 result = groupChatMsg.groupChatMsgGcresult;
    
    NSInteger index = [self chatMsgIsSending:msgNum];
    if (index >= 0) {
        [self.msgArray removeObjectAtIndex:index];
    }else {
        return;
    }
    
    ChatMsgSendStatus status ;
    if (result == 1) {
        status = ChatMsgSendStatusSuccess;
    }else if (result == 2) {
        status = ChatMsgSendStatusFail;
    }
    
    [self updateSendStatusWithDbId:msgNum status:status];
}

#pragma mark - private
- (void)sendInsertChatMsgNotificationWithMsgArray:(NSArray *)chatMsgArray
{
    NSMutableArray *array = [NSMutableArray array];
    for (GroupChatMsg *chatMsg in chatMsgArray) {
        UInt64 groupId = [CurrentChat shareInstance].chatGroup.group_id;
        if (chatMsg.groupId == groupId) {
            [array addObject:chatMsg];
        }
    }
    
    if (array.count > 0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"AddNewPrivateChatMsg" object:array];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ChatInfoReload" object:nil];
}

- (void)sendUpdateChatMsgSendStatusWithId:(UInt64)dbId status:(ChatMsgSendStatus)status
{
    NSDictionary *dict = @{@"dbId":[NSNumber numberWithLongLong:dbId],
                           @"status":[NSNumber numberWithInteger:status]};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"UpdateChatMsgStatus" object:nil userInfo:dict];
}

- (void)updateSendStatusWithDbId:(UInt64)dbId status:(ChatMsgSendStatus)status
{
    BOOL ret = [[GroupMsgDao shareInstance] updateSendStatusWithDbId:dbId status:status];
    if (ret) {
        NSLog(@"更新发送状态成功!");
        [self sendUpdateChatMsgSendStatusWithId:dbId status:status];
    }else {
        NSLog(@"更新发送状态失败!");
    }
}
#pragma mark - 超时处理
- (void)handleTimer:(NSTimer *)timer
{
    dispatch_async([IM_Service instance].serviceQueue, ^{
        
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
        
        NSMutableArray *removeArray = [NSMutableArray array];
        
        for (GroupChatMsg *chatMsg in self.msgArray) {
            if ((time - chatMsg.createTime/1000) > 60.0f) {
                chatMsg.sendStatus = ChatMsgSendStatusFail;
                [self updateSendStatusWithDbId:chatMsg.dbId status:ChatMsgSendStatusFail];
                [removeArray addObject:chatMsg];
            }
        }
        [self.msgArray removeObjectsInArray:removeArray];
    });
    
}

- (void)dealloc
{
    self.timer = nil;
}
@end
